package com.xayy.health.core.antlr4.utils;

import java.util.*;

import org.springframework.stereotype.Component;

import com.xayy.health.mgt.model.TelemetryData;
import com.xayy.health.mgt.model.dto.DataFeatureDto;
import com.xayy.health.mgt.service.SatelliteNodeService;

import cn.kawins.spring.utils.SpringHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * @author Nie
 * @version V1.0 @ Date 2024/6/4 17:05
 */
@Component
@Slf4j
public class CsUtil {

    public static Double getCSScore(String satCode, String paramCode, Date evaluationTime) {
        Double value = Golabl.getValue(satCode, paramCode);
        if (value != null){
            return value;
        }
        DataFeatureDto dataFeatureDto = new DataFeatureDto();
        dataFeatureDto.setSatelliteCode(satCode);
        dataFeatureDto.setParamCode(paramCode);
        Calendar now = Calendar.getInstance();
        now.setTime(evaluationTime);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - 1);
        Date startTime = now.getTime();
        dataFeatureDto.setStartTime(startTime);
        dataFeatureDto.setEndTime(evaluationTime);
        dataFeatureDto.setTimeInterval(60);
        SatelliteNodeService satelliteNodeService = SpringHolder.getBean(SatelliteNodeService.class);
        List<TelemetryData> ycList = null;
        try {
            ycList = satelliteNodeService.getYcList(dataFeatureDto);
        } catch (Exception e) {
            log.info("getCSScore errors...",e);
            Golabl.setValue(satCode, paramCode, 0d);
           return 0d;
        }
        List<TelemetryData> finList = new ArrayList<>();
        for(TelemetryData data:ycList){
          if(!StringUtils.isEmpty(data.getValue())){
              finList.add(data);
           }
        }
        OptionalDouble average = finList.stream().mapToDouble(TelemetryData::getDoubleValue).average();
        if (average.isPresent()) {
            Golabl.setValue(satCode, paramCode, average.getAsDouble());
            return average.getAsDouble();
        }
        Golabl.setValue(satCode, paramCode, 0d);
        return 0d;
    }
}
